package cn.yanhu.kuwanapp.home

import android.content.Context
import android.content.Intent
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.navigation.TabBottomNavigation
import cn.woochen.comlib.navigation.iterator.ListTabIterator
import cn.woochen.comlib.util.*
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.bean.response.RespHomeTabBean
import cn.yanhu.kuwanapp.common.viewmodels.CommonViewModel
import cn.yanhu.kuwanapp.databinding.ActivityMainBinding
import cn.yanhu.kuwanapp.earn.fragment.EarnFragment
import cn.yanhu.kuwanapp.event.VideoRewardEvent
import cn.yanhu.kuwanapp.home.fragment.HomeFragment
import cn.yanhu.kuwanapp.home.fragment.WelfareFragment
import cn.yanhu.kuwanapp.http.UrlConstainer
import cn.yanhu.kuwanapp.invite.InviteFragment
import cn.yanhu.kuwanapp.my.MyFragment
import cn.yanhu.kuwanapp.my.activity.MySmallGameActivity
import cn.yanhu.kuwanapp.user.UserViewModel
import cn.yanhu.kuwanapp.utils.Config
import cn.yanhu.kuwanapp.utils.DeviceInfoUtil
import cn.yanhu.kuwanapp.utils.SimpleDialogUtil
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.parseState
import cn.yanhu.kuwanapp.utils.ext.showToast
import cn.yanhu.kuwanapp.utils.helper.ApkUpdateHelper
import cn.yanhu.kuwanapp.utils.third.AccountType
import cn.yanhu.kuwanapp.utils.third.ThirdAccountHelper
import cn.yanhu.kuwanapp.welfare.WelfareViewModel
import cn.yanhu.kuwanapp.widgets.TabMainView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lz.aiwan.littlegame.bean.AdConfig
import com.lz.aiwan.littlegame.bean.GameCenterConfig
import com.lz.aiwan.littlegame.bean.IGamePlayCallback
import com.lz.aiwan.littlegame.utils.LzLittleGame
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yilan.sdk.ui.little.YLLittleVideoFragment

/**
 * 首页
 */
class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>(), OnSingleClickListener {

    private val mCommonViewModel by viewModels<CommonViewModel>()
    private val mUserViewModel by viewModels<UserViewModel>()
    private var mImei by UserPref(Constants.IMEI, "")
    private var exitTime: Long = 0

    override fun setContentView(): Int = R.layout.activity_main

    private val apkUpdateHelper by lazy {
        ApkUpdateHelper()
    }

    private fun getUserInfo(){
        mUserViewModel.userInfo("0")
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //检测更新
        mCommonViewModel.checkUpdateData.observe(this, Observer { it ->
            parseState(it, {
                apkUpdateHelper.update(this, it)
            })
        })
        //tab信息
        mViewModel.homeTabInfo.observe(this, Observer { it ->
            parseState(it, { it ->
                mTabDatas.clear()
                it.forEach {
                    when (it.subTitle) {
                        EXTRA_TAB_HOME -> {
                            it.icon = R.drawable.select_tab_home
                        }
                        EXTRA_TAB_EARN -> {
                            it.icon = R.drawable.select_tab_earn
                        }
                        EXTRA_TAB_INVITE -> {
                            it.icon = R.drawable.select_tab_invite
                        }
                        EXTRA_TAB_WELFARE -> {
                            it.icon = R.drawable.select_tab_welfare
                        }
                        EXTRA_TAB_MY -> {
                            it.icon = R.drawable.select_tab_my
                        }
                    }
                    if (it.status == "1") mTabDatas.add(it)
                    if (it.hasExam == "1") Constants.isExamine = true
                }
                initBottomNav()
                initFragments()
            })
        })
        //金币奖励领取事件
        LiveEventBus.get(VideoRewardEvent::class.java).observe(this, Observer {
            when (it.source) {
                VideoRewardEvent.SOURCE_HOME -> {
                    mWelfareViewModel.videoReward(businessType = it.businessType)
                }
                else -> {
                }
            }
        })
        //金币奖励领取
        mWelfareViewModel.videoRewardInfo.observe(this, Observer {
            parseState(it, {
                getUserInfo()
                SimpleDialogUtil.create(mContext, layoutRes = R.layout.dialog_receive_coin)?.apply {
                    val llContent = getView<ViewGroup>(R.id.ll_content)
                    val tvGold = getView<TextView>(R.id.tv_gold)
                    tvGold?.text = it.amount
                    llContent?.setOnClickListener {
                        dismiss()
                    }
                }?.show()
            })
        })
    }

    private val mRxPermissions by lazy {
        RxPermissions(this)
    }

    private val mWelfareViewModel by viewModels<WelfareViewModel>()

    override fun initData() {
        if (mImei.isBlank()){
            mRxPermissions.request(android.Manifest.permission.READ_PHONE_STATE).subscribe {
                if (it){
                    mImei = DeviceInfoUtil.getIMEI(ApplicationUtil.context)
                }
            }
        }
        mCommonViewModel.checkUpdate()
        initGameSdk()
        initWidgets()
        initVideoSdk()
        mCommonViewModel.eventTrace(Constants.EVENT_KEY_APP_HOME_VIEW)
    }


    private fun initVideoSdk() {
        //建议放在小视频页面展示之前调用，例如在Splash页面或MainActivity中调用
        YLLittleVideoFragment.preloadVideo()
    }

    /**
     * 初始化tab信息
     *
     */
    private fun initTabInfo() {
        mViewModel.homeTab()
    }

    private var mUserId by UserPref(Constants.USER_ID, "")
    private var mNickname by UserPref(Constants.USER_NICKNAME, "")
    private var mHeadUrl by UserPref(Constants.USER_HEAD_URL, "")

    /**
     * 初始化游戏sdk
     */
    private fun initGameSdk() {
        val adConfig = AdConfig().apply {
            ttRewardVideo_h_code = Constants.GAME_TTREWARDVIDEO_H_CODE //穿山甲横屏激励视屏广告位id
            ttRewardVideo_v_code = Constants.GAME_TTREWARDVIDEO_V_CODE //穿山甲竖屏激励视频广告位id
            ttFullVideo_h_code = Constants.GAME_TTFULLVIDEO_H_CODE //穿山甲横屏全屏视频广告位id
            ttFullVideo_v_code = Constants.GAME_TTFULLVIDEO_V_CODE //穿山甲竖屏全屏视频广告位id
            ttNativeCode_New = Constants.GAME_TTNATIVECODE_NEW //穿山甲新插屏id(竖屏)
            ttNativeExpressAd = Constants.GAME_TTNATIVEEXPRESSAD //穿山甲信息流游戏弹框广告
            isBooleanhideFnishGameDialog = false //是否隐藏游戏结束时候确认退出dialog。默认不隐藏
            userid = mUserId //必填
            headUrl = mHeadUrl
            nickName = mNickname
        }
        val gameCenterConfig = GameCenterConfig()
        LzLittleGame.getInstance().LaunchLGSDK(
            mContext,
            Config.GAME_APP_ID,
            Config.GAME_APP_key,
            adConfig,
            gameCenterConfig,
            UrlConstainer.SHOW_LOG
        )
    }

    private fun initWidgets() {

    }

    override fun onStart() {
        super.onStart()
        if (mTabDatas.isEmpty()) {
            initTabInfo()
        }
    }

    private fun initFragments() {
        mFragmentManagerHelper.clear()
        //默认添加一个fragment
        val desFragment = mFragmentManagerHelper.findFragmentByTag(mTabDatas[0].subTitle)
        if (desFragment == null) {
            mFragmentManagerHelper.addFragment(HomeFragment.newInstance(), mTabDatas[0].subTitle)
        }
    }

    private val mFragmentManagerHelper by lazy {
        FragmentManagerHelper(supportFragmentManager, R.id.fl_container)
    }

    override fun onDestroy() {
        super.onDestroy()
        LzLittleGame.getInstance().onSdkDestory()
    }

    private val mTabDatas by lazy {
        mutableListOf<RespHomeTabBean>()
    }
    private val mTabIterator = ListTabIterator<TabMainView>()

    /**
     * 初始化底部导航
     */
    private fun initBottomNav() {
        mTabIterator.clear()
        mBinding.bottomNav.setItemGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM)
        for (tabBean in mTabDatas) {
            val tabMainView = TabMainView.Builder(mContext).name(tabBean.title).icon(tabBean.icon)
                .build<TabMainView>()
            mTabIterator.addItem(tabMainView)
        }
        mBinding.bottomNav.addItem(mTabIterator)
        mBinding.bottomNav.onItemClickListener = object : TabBottomNavigation.OnItemClickListener {
            override fun onItemClick(position: Int) {
                val tabTag = mTabDatas[position].subTitle
                switchTab(tabTag)
            }
        }
    }

    private var currentTag = ""

    fun switchTab(tabTag: String) {
        currentTag = tabTag
        val indexOfFirst = mTabDatas.indexOfFirst { it.subTitle == tabTag }
        mCommonViewModel.eventTrace(Constants.EVENT_KEY_APP_TAB_CLICK,mTabDatas[indexOfFirst].title)
        mBinding.bottomNav.selectItem(indexOfFirst)
        var desFragment = mFragmentManagerHelper.findFragmentByTag(tabTag)
        when (tabTag) {
            EXTRA_TAB_HOME -> { //首页
                setStatusBarStyle(true)
                if (desFragment != null && desFragment is HomeFragment) {
                    desFragment.refreshData()
                } else {
                    desFragment = HomeFragment.newInstance()
                }
                mFragmentManagerHelper.swithFragmentAllowingStateLoss(desFragment, tabTag)
            }
            EXTRA_TAB_EARN -> { //赚钱
                setStatusBarStyle(false)
                if (desFragment != null && desFragment is EarnFragment) {
                    desFragment.refreshData()
                } else {
                    desFragment = EarnFragment.newInstance()
                }
                mFragmentManagerHelper.swithFragmentAllowingStateLoss(desFragment, tabTag)
            }
            EXTRA_TAB_INVITE -> { //邀请
                setStatusBarStyle(true)
                if (desFragment != null && desFragment is InviteFragment) {
                    desFragment.refreshData()
                } else {
                    desFragment = InviteFragment.newInstance(mTabDatas[indexOfFirst].url)
                }
                mFragmentManagerHelper.swithFragmentAllowingStateLoss(desFragment, tabTag)
            }
            EXTRA_TAB_WELFARE -> { //福利
                setStatusBarStyle(true)
                if (desFragment != null && desFragment is WelfareFragment) {
                    desFragment.refreshData()
                } else {
                    desFragment = WelfareFragment.newInstance(mTabDatas[indexOfFirst].url)
                }
                mFragmentManagerHelper.swithFragmentAllowingStateLoss(desFragment, tabTag)

            }
            EXTRA_TAB_MY -> { //我的
                setStatusBarStyle(true)
                if (desFragment != null && desFragment is MyFragment) {
                    desFragment.refreshData()
                } else {
                    desFragment = MyFragment.newInstance()
                }
                mFragmentManagerHelper.swithFragmentAllowingStateLoss(desFragment, tabTag)
            }

        }
    }

    override fun initListener() {
        LzLittleGame.getInstance().setGamePlayCallback(object : IGamePlayCallback {
            override fun gamePlayTimeCallback(context: Context?, gameid: String?, gamename: String?, playTimeInSeconds: Int) {
                logcom("小游戏时长回调：gameid:${gameid} gameName:${gamename} time:${playTimeInSeconds}")
                var money = 0
                if (playTimeInSeconds <= 30){
                    money = 0
                }else if (playTimeInSeconds <= 360){
                    money = playTimeInSeconds / 3
                }else{
                    money = 120
                }
                logcom("currentActivity:${PackageUtil.currentActivity }")
                if (money > 0){
                    if (containsTargetActivity(MySmallGameActivity::class.java.simpleName)){//如果不是当前页监听到的，通知指定页面进行处理
                        LiveEventBus.get(VideoRewardEvent::class.java).post(VideoRewardEvent(VideoRewardEvent.SOURCE_SMALL_GAME_LIST,"4",money.toString(),gamename?:""))
                    }else{
                        mWelfareViewModel.videoReward(money.toString(),"4",gamename?:"")
                    }
                }

            }

            override fun gameClickCallback(gameid: String?, gamename: String?) {

            }
        });
    }

    /**
     * 是否包含指定的Activity
     * @return Boolean
     */
    private fun containsTargetActivity(targetActivityName:String):Boolean{
        var hasContain = false
        ActivityUtil.activities.forEach {
            if (it.javaClass.simpleName == targetActivityName) hasContain = true
        }
        return hasContain
    }

    override fun requestData() {

    }

    private val mTabTag by lazy {
        intent.getStringExtra(EXTRA_TAB_TAG)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        val tabTag = intent?.getStringExtra(EXTRA_TAB_TAG) ?: EXTRA_TAB_HOME
        switchTab(tabTag)
    }

    companion object {
        const val EXTRA_TAB_HOME = "home_page"
        const val EXTRA_TAB_EARN = "earn"
        const val EXTRA_TAB_INVITE = "invite"
        const val EXTRA_TAB_WELFARE = "welfare"
        const val EXTRA_TAB_MY = "my"
        private const val EXTRA_TAB_TAG = "extra_index"

        fun start(context: Context, tabTag: String = EXTRA_TAB_HOME) {
            val intent = Intent(context, MainActivity::class.java)
            intent.putExtra(EXTRA_TAB_TAG, tabTag)
            context.startActivity(intent)
        }
    }


    override fun onBackPressed() {
        if (currentTag == EXTRA_TAB_INVITE){
            val desFragment = mFragmentManagerHelper.findFragmentByTag(currentTag)
            if (desFragment is InviteFragment && !desFragment.canBack()){
                toFinish()
            }
        }else if (currentTag == EXTRA_TAB_WELFARE){
            val desFragment = mFragmentManagerHelper.findFragmentByTag(currentTag)
            if (desFragment is WelfareFragment && !desFragment.canBack()){
                toFinish()
            }
        } else{
           toFinish()
        }
    }

    private fun toFinish(){
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast(R.string.tip_exit)
            exitTime = System.currentTimeMillis()
        } else {
            ActivityUtil.appExit(mContext)
        }
    }

    override fun onSingleClick(v: View?) {

    }
}